<?php
/**
 * @package YARBB
 * @copyright Авторские права (C) 2009 www.yar-it.com. Все права защищены.
 * @license Лицензия http://www.gnu.org/licenses/gpl-2.0.htm GNU/GPL, или help/license.php
 * YARBB! - свободное программное обеспечение распространяемое по условиям лицензии GNU/GPL
 * Для получения информации о используемых расширениях и замечаний об авторском праве, смотрите файл copyright.php.
 */

// no direct access
defined( '_VALID_MOS' ) or die( 'Direct Access to this location is not allowed.' );
// If we are running pre PHP 4.2.0, we add our own implementation of var_export
//
if (!function_exists('var_export')) {
	function var_export() {
		$args = func_get_args();
		$indent = (isset($args[2])) ? $args[2] : '';
		if (is_array($args[0])) {
			$output = 'array ('."\n";
			foreach ($args[0] as $k => $v) {
				if (is_numeric($k))
					$output .= $indent.'  '.$k.' => ';
				else
					$output .= $indent.'  \''.str_replace('\'', '\\\'', str_replace('\\', '\\\\', $k)).'\' => ';
				if (is_array($v))
					$output .= var_export($v, true, $indent.'  ');
				else {
					if (gettype($v) != 'string' && !empty($v))
						$output .= $v.','."\n";
					else
						$output .= '\''.str_replace('\'', '\\\'', str_replace('\\', '\\\\', $v)).'\','."\n";
				}
			}
			$output .= ($indent != '') ? $indent.'),'."\n" : ')';
		}
		else
			$output = $args[0];
		if ($args[1] == true)
			return $output;
		else
			echo $output;
	}
}
//
// Generate the config cache PHP script
//
function generate_config_cache() {
	global $database, $yarbb_admin_path;
	// Получаем конфиг из базы
	$database->setQuery('SELECT * FROM #__forum_config');
	$rows=$database->loadRowList();

	foreach($rows as $cur_config_item )
		$output[$cur_config_item[0]] = $cur_config_item[1];
	// Конфиг как PHP
	$fh = @fopen($yarbb_admin_path.'/cache/cache_config.php', 'wb');
	if (!$fh)
		mosRedirect('index2.php?option=com_forum', 'Unable to write configuration cache file to cache directory. Please make sure PHP has write access to the directory cache');
	fwrite($fh, '<?php'."\n\n".'define(\'YARBB_CONFIG_LOADED\', 1);'."\n\n".'$yarbb_config = '.var_export($output, true).';'."\n\n".'?>');
	fclose($fh);
}
//
// Generate the bans cache PHP script
//
function generate_bans_cache() {
	global $database, $yarbb_admin_path;
	// Get the ban list from the DB
	//s?
	$database->setQuery('SELECT * FROM #__forum_bans');
	$rows = $database->loadAssocList();

	$output = array();
	foreach($rows as $cur_ban )
		$output[] = $cur_ban;
	// Output ban list as PHP code
	$fh = @fopen($yarbb_admin_path.'/cache/cache_bans.php', 'wb');
	if (!$fh)
		mosRedirect('index2.php?option=com_forum', 'Unable to write configuration cache file to cache directory. Please make sure PHP has write access to the directory cache');
	fwrite($fh, '<?php'."\n\n".'define(\'YARBB_BANS_LOADED\', 1);'."\n\n".'$yarbb_bans = '.var_export($output, true).';'."\n\n".'?>');
	fclose($fh);
}
//
// Generate the ranks cache PHP script
//
function generate_ranks_cache() {
	global $database, $yarbb_admin_path;
	// Get the rank list from the DB
	//s
	$database->setQuery('SELECT * FROM #__forum_ranks ORDER BY min_posts');
	$rows = $database->loadAssocList();

	$output = array();
	foreach ($rows as $cur_rank )
		$output[] = $cur_rank;
	// Output ranks list as PHP code
	$fh = @fopen($yarbb_admin_path.'/cache/cache_ranks.php', 'wb');
	if (!$fh)
		mosRedirect('index2.php?option=com_forum', 'Unable to write configuration cache file to cache directory. Please make sure PHP has write access to the directory cache');
	fwrite($fh, '<?php'."\n\n".'define(\'YARBB_RANKS_LOADED\', 1);'."\n\n".'$yarbb_ranks = '.var_export($output, true).';'."\n\n".'?>');
	fclose($fh);
}
//
// Generate quickjump cache PHP scripts
//
function generate_quickjump_cache($group_id = false) {
	global $database, $yarbb_user, $yarbb_admin_path;
	// If a group_id was supplied, we generate the quickjump cache for that group only
	if ($group_id !== false)
		$groups[0] = $group_id;
	else {
		// A group_id was now supplied, so we generate the quickjump cache for all groups
		//s?
		$database->setQuery('SELECT g_id FROM #__forum_groups');
		$num_groups = $database->getNumRows();
		$rows=$database->loadResultArray();
		for ($i = 0; $i < $num_groups; ++$i)
			$groups[] = $rows[$i];
	}
	// Loop through the groups in $groups and output the cache for each of them
	while (list(, $group_id) = @each($groups)) {
		// Output quickjump as PHP code
		$fh = @fopen($yarbb_admin_path.'/cache/cache_quickjump_'.$group_id.'.php', 'wb');
		if (!$fh)
			mosRedirect('index2.php?option=com_forum', 'Unable to write configuration cache file to cache directory. Please make sure PHP has write access to the directory cache');
		$output = '<?php'."\n\n".'if (!defined(\'YARBB\')) exit;'."\n".'define(\'YARBB_QJ_LOADED\', 1);'."\n\n".'?>';
		$output .= "\t\t\t\t".'<form id="qjump" method="get" action="'.YARBB_URL.'&amp;task=index&amp;task=viewforum">'."\n\t\t\t\t\t".'<div><label><?php echo _Y_LINKTO ?>'."\n\n\t\t\t\t\t".'<select name="id" onchange="window.location=(\'<?php echo YARBB_URL?>&amp;task=viewforum&amp;id=\'+this.options[this.selectedIndex].value)">'."\n";

		//s
		$database->setQuery('SELECT c.id AS cid, c.cat_name, f.id AS fid, f.forum_name, f.redirect_url, f.parent_forum_id FROM #__forum_categories AS c INNER JOIN #__forum_forums AS f ON c.id=f.cat_id LEFT JOIN #__forum_forum_perms AS fp ON (fp.forum_id=f.id AND fp.group_id='.$group_id.') WHERE fp.read_forum IS NULL OR fp.read_forum=1 ORDER BY c.disp_position, c.id, f.disp_position', true);
		$rows=$database->loadAssocList();
		$cur_category = 0;
		foreach($rows as $cur_forum ) {
			if ($cur_forum['cid'] != $cur_category)	// A new category since last iteration?
			{
				if ($cur_category)
					$output .= "\t\t\t\t\t\t".'</optgroup>'."\n";
				$output .= "\t\t\t\t\t\t".'<optgroup label="'.yarbb_htmlspecialchars($cur_forum['cat_name']).'">'."\n";
				$cur_category = $cur_forum['cid'];
			}
			$redirect_tag = ($cur_forum['redirect_url'] != '') ? ' &gt;&gt;&gt;' : '';
			if ($cur_forum['parent_forum_id'] == 0) {
				$output .= "\t\t\t\t\t\t\t".'<option value="'.$cur_forum['fid'].'"<?php echo ($forum_id == '.$cur_forum['fid'].') ? \' selected="selected"\' : \'\' ?>>'.yarbb_htmlspecialchars($cur_forum['forum_name']).$redirect_tag.'</option>'."\n";
			}
			else {
				$output .= "\t\t\t\t\t\t\t".'<option value="'.$cur_forum['fid'].'"<?php echo ($forum_id == '.$cur_forum['fid'].') ? \' selected="selected"\' : \'\' ?>>&nbsp;&nbsp;&nbsp;'.yarbb_htmlspecialchars($cur_forum['forum_name']).$redirect_tag.'</option>'."\n";
			}
		}
		$output .= "\t\t\t\t\t".'</optgroup>'."\n\t\t\t\t\t".'</select>'."\n\t\t\t\t\t".'<input type="submit" value="<?php echo _MENU_NEXT ?>" accesskey="g" />'."\n\t\t\t\t\t".'</label></div>'."\n\t\t\t\t".'</form>'."\n";
		fwrite($fh, $output);
		fclose($fh);
	}
}
//
// Generate the adsense config cache PHP script
//
function generate_adsense_config_cache() {
	global $database, $yarbb_admin_path;
	// Get the forum config from the DB
	//s?
	$database->setQuery('SELECT * FROM #__forum_adsense_config');
	$rows=$database->loadRowList();

	foreach ($rows as $cur_config_item )
		$output[$cur_config_item[0]] = $cur_config_item[1];
	// Output config as PHP code
	$fh = @fopen($yarbb_admin_path.'/cache/cache_adsense_config.php', 'wb');
	if (!$fh)
		mosRedirect('index2.php?option=com_forum', 'Unable to write configuration cache file to cache directory. Please make sure PHP has write access to the directory cache');
	fwrite($fh, '<?php'."\n\n".'define(\'YARBB_ADSENSE_CONFIG_LOADED\', 1);'."\n\n".'$adsense_config = '.var_export($output, true).';'."\n\n".'?>');
	fclose($fh);
}